﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FCDB.WEB.Models
{
    public interface IPagedList
    {
        int CurrentPageIndex { get; set; }
        int PageSize { get; set; }
        int TotalItemCount { get; set; }
        int TotalPageCount { get; }
        int StartRecordIndex { get; }
        int EndRecordIndex { get; }
    }
     [Serializable]
    public class PagedList<T> : List<T>, IPagedList
    {
        
        public PagedList(IList<T> items, int pageIndex, int pageSize)
        {
            PageSize = pageSize;

            CurrentPageIndex = pageIndex;
            if (items != null)
            {
                TotalItemCount = items.Count;
                for (int i = StartRecordIndex - 1; i < EndRecordIndex; i++)
                {
                    Add(items[i]);
                }
            }
        }
        
        public PagedList(IEnumerable<T> items, int pageIndex, int pageSize, int totalItemCount)
        {
            if (items != null)
            {
                AddRange(items);
            }

            TotalItemCount = totalItemCount;

            int maxPageIndex = (int) Math.Ceiling(totalItemCount/(double) pageSize);
            ;

            if (pageIndex > maxPageIndex)
            {
                CurrentPageIndex = 1;
            }
            else
            {
                CurrentPageIndex = pageIndex;
            }
            PageSize = pageSize;
        }

        public int CurrentPageIndex { get; set; }
        public int PageSize { get; set; }
        public int TotalItemCount { get; set; }

        public int TotalPageCount
        {
            get { return (int) Math.Ceiling(TotalItemCount/(double) PageSize); }
        }

        public int StartRecordIndex
        {
            get { return (CurrentPageIndex - 1)*PageSize + 1; }
        }

        public int EndRecordIndex
        {
            get { return TotalItemCount > CurrentPageIndex*PageSize ? CurrentPageIndex*PageSize : TotalItemCount; }
        }
    }
}